package mammuthus.docker

import com.github.dockerjava.core.DockerClientBuilder
import com.google.inject.{Inject, Singleton}
import net.csdn.common.settings.Settings
import mammuthus.tool.SystemTool
import scala.collection.JavaConversions._

/**
 * 5/10/15 WilliamZhu(allwefantasy@gmail.com)
 */
@Singleton
class DockerClient @Inject()(conf: Settings) {

  val dockerClient = if (SystemTool.docker.enable) Some(DockerClientBuilder.getInstance(conf.get("docker.url", "unix:///var/run/docker.sock")).build())
  else None

  def createContainer(name: String, image: String) = {
    dockerClient match {
      case Some(dc) =>
        val container = dc.createContainerCmd(image).withName(name).exec()
        (container.getId, name)
      case None => ("-", name)
    }
  }

  def startContainer(id: String) = {
    dockerClient match {
      case Some(dc) =>
        dc.execStartCmd(id).withDetach(true).withTty(false).exec()
      case None =>
    }
  }

  def stopContainer(id: String) = {
    dockerClient match {
      case Some(dc) =>
        dc.stopContainerCmd(id).withTimeout(15).exec()
      case None =>
    }
  }

  def listContainer = {
    dockerClient match {
      case Some(dc) =>
      dc.listContainersCmd().withShowAll(true).exec().toList
      case None => List()
    }
  }
}
